import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getRouters } from '@/api/login'
import { logout } from '@/api/logout'
import { getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import Layout from '@/layout'
import ParentView from '@/components/ParentView'
const _import = require('@/router/_import_' + process.env.NODE_ENV) // 获取组件的方法

const state = {
  permissions: [], // 按钮权限
  routers: constantRoutes, // 路由菜单
  roles: [], // 角色信息
  token: getToken(), // 从缓存中读取
  userInfo: {} // 存储用户信息
}
// 用来修改state中的数据
const mutations = {
  // 设置token
  SET_TOKEN: (state, token) => {
    state.token = token
    // 将我们请求接口拿到的token通过setToken()这个方法设置到缓存中去
    setToken(token)
  },
  // 设置用户信息
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  // 设置角色信息
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  // 清除token
  REMOVE_TOKEN: state => {
    state.token = ''
    // 清除缓存中的token
    removeToken()
  },
  // 设置按钮权限
  SET_PEMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  // 设置路由权限
  SET_ROUTERS: (state, routers) => {
    state.routers = [...constantRoutes, ...routers] // 静态路由和动态路由合并
  }
}
// 异步方法
const actions = {
  // 用户登录
  async login(context, fromData) {
    // 1:调用登录接口,拿到返回的token ,解构对象
    const { Authorization } = await login(fromData)
    // 2:拿到token之后使用commit调用mutation中的setToken()方法
    context.commit('SET_TOKEN', Authorization)
  },
  // 获取用户信息
  async getUserInfo(context) {
    const resault = await getUserInfo()
    // 保存用户信息
    context.commit('SET_USERINFO', resault.sysUser)
    // 保存按钮权限
    context.commit('SET_PEMISSIONS', resault.permissions)
    // 保存角色信息
    context.commit('SET_ROLES', resault.roles)
    return resault // 返回给调用者
  },
  // 退出登录
  async logout(context) {
    // 请求后台退出登录
    await logout()
    // 重置路由信息
    resetRouter()
    // 删除token
    context.commit('REMOVE_TOKEN')
    // 清理用户信息
    context.commit('SET_USERINFO', {})
    // 清理按钮权限
    context.commit('SET_PEMISSIONS', [])
    // 清理角色信息
    context.commit('SET_ROLES', [])
    // 清理菜单权限
    context.commit('SET_ROUTERS', [])
  },
  // 获取路由信息
  async getRouters(context) {
    const routerData = await getRouters()
    const dynamicRouting = filterAsyncRouter(routerData)
    context.commit('SET_ROUTERS', dynamicRouting)
    return dynamicRouting
  },
  // 清除Vuex缓存数据
  clearVuex(context) {
    // 删除token
    context.commit('REMOVE_TOKEN')
    // 清理用户信息
    context.commit('SET_USERINFO', {})
    // 清理按钮权限
    context.commit('SET_PEMISSIONS', [])
    // 清理角色信息
    context.commit('SET_ROLES', [])
    // 清理菜单权限
    context.commit('SET_ROUTERS', [])
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        try {
          route.component = _import(route.component) // 导入组件
        } catch (error) {
          console.log(error)
          route.component = _import('dashboard/index') // 导入组件
        }
      }
    }
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRouter(route.children)
    } else {
      delete route.children
    }
    return true
  })
  return accessedRouters
}

// 遍历后台传来的路由字符串，转换为组件对象
// function filterAsyncRouter(asyncRouterMap) {
//   const accessedRouters = asyncRouterMap.filter(route => {
//     const item = route.component
//     if (route.component) {
//       if (route.component === 'Layout') {
//         route.component = Layout
//       } else if (route.component === 'ParentView') {
//         route.component = ParentView
//       } else {
//         try {
//           route.component = (resolve) => require([`@/views/${item}.vue`], resolve) // 导入组件
//         } catch (error) {
//           route.component = (resolve) => require([`@/views/dashboard/index.vue`], resolve) // 导入组件
//         }
//       }
//     }
//     if (route.children && route.children.length > 0) {
//       route.children = filterAsyncRouter(route.children)
//     } else {
//       delete route.children
//     }
//     return true
//   })
//   return accessedRouters
// }
